<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      class="form-container"
    >
      <div class="createPost-main-container">
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1">
            <template slot="title">
              <i class="header-icon el-icon-info"></i>基础信息
            </template>
            <el-row gutter="80">
              <div class="postInfo-container">
                <el-col :span="12">
                  <el-row>
                    <el-form-item
                     style="margin-bottom: 40px"
                      label-width="180px"
                      label="项目名称:"
                      prop="projectName"
                    >
                    <el-input
                        v-model="postForm.projectName"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                     style="margin-bottom: 40px"
                      label-width="180px"
                      label="所属课题组:"
                      prop="projectGroupName"
                    >
                      <el-input
                        v-model="postForm.projectGroupName"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectDepartment"
                      label-width="180px"
                      label="所属部门："
                    >
                      <el-input
                        v-model="postForm.projectDepartment"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectApprovedCost"
                      label-width="180px"
                      label="批准经费："
                    >
                      <el-input
                        v-model="postForm.projectApprovedCost"
                        :maxlength="100"
                        name="name"
                        required
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                </el-col>
                <el-col :span="12">
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectOwnerName"
                      label-width="180px"
                      label="项目负责人："
                    >
                      <el-input
                        v-model="postForm.projectOwnerName"
                        :maxlength="100"
                        name="name"
                        required
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectOwnerEmployeeId"
                      label-width="180px"
                      label="负责人员工编号："
                    >
                      <el-input
                        v-model="postForm.projectOwnerEmployeeId"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectOwnerPhone"
                      label-width="180px"
                      label="负责人电话："
                    >
                      <el-input
                        v-model="postForm.projectOwnerPhone"
                        :maxlength="100"
                        name="name"
                        required
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>

                  <el-row>
                    <el-form-item
                      style="margin-bottom: 40px"
                      prop="projectOwnerEmail"
                      label-width="180px"
                      label="负责人邮箱："
                    >
                      <el-input
                        v-model="postForm.projectOwnerEmail"
                        :maxlength="100"
                        name="name"
                        disabled
                      >
                      </el-input>
                    </el-form-item>
                  </el-row>
                </el-col>
              </div>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="1" v-if="postForm.projectMidReportName || isMidReport">
            <template slot="title">
              <i class="header-icon el-icon-info"></i>中检信息
            </template>
            <el-row>
              <el-row>
                <el-form-item
                    label-width="230px"
                    label="前期经费使用情况："
                    class="postInfo-container-item"
                    prop="projectAppliedCostItems"
                >
                  <el-table
                      class="appropriation-table"
                      :data="postForm.projectAppliedCostUseItems"
                      border
                  >
                    <el-table-column label="经费科目" width="300px" align="center">
                      <template slot-scope="{ row }">
                        <el-input
                            v-model="row.id"
                        >
                        </el-input>
                      </template>
                    </el-table-column>
                    <el-table-column width="200px" align="center" label="使用金额（万元）">
                      <template slot-scope="{ row }">
                        <el-input
                            v-model="row.appropriation"
                            :maxlength="100"
                            name="name"
                            type="number"
                            @change="computedMoney"
                        >
                        </el-input>
                      </template>
                    </el-table-column>
                    <el-table-column width="200px" align="center" label="操作">
                      <template slot-scope="scope">
                        <div class="block float-right">
                          <el-button
                              round
                              @click="removeItem(scope.row.index)"
                              icon="delete"
                          >
                            删除
                          </el-button>
                          <el-button
                              round
                              v-if="
                          scope.$index + 1 ===
                          postForm.projectAppliedCostUseItems.length
                        "
                              @click="addItem(scope.$index)"
                          >
                            添加
                          </el-button>
                        </div>
                      </template>
                    </el-table-column>

                  </el-table>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                    style="margin-bottom: 40px"
                    prop="projectAppliedCost"
                    label-width="230px"
                    label="已使用经费（万元）："
                >
                  <el-input
                      v-model="postForm.projectAppliedCostUse"
                      :maxlength="100"
                      name="name"
                  >
                  </el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item label-width="180px" label="中检报告：">
                  <el-upload
                    class="file-uploader"
                    action="http://localhost:3001/api/projects/upload"
                    :limit="1"
                    :on-preview="handlePreview"
                    :before-remove="beforeRemove"
                    :on-exceed="handleExceed"
                    :on-success="handleSuccess"
                    :file-list="midFileList"
                  >
                    <el-button size="small" type="primary"
                      v-if="isMidReport && checkProjectOwner(postForm.id, postForm.projectApplicantId) && !isView">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip" v-if="isMidReport && checkProjectOwner(postForm.id) && !isView">
                      .docs 文件小于500kb
                    </div>
                  </el-upload>
                </el-form-item>
              </el-row>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="1" v-if="postForm.projectFinalReportName || isFinalReport">
            <template slot="title">
              <i class="header-icon el-icon-info"></i>结项信息
            </template>
            <el-row>
              <el-row>
                <el-form-item label-width="180px" label="结项报告：">
                  <el-upload
                    class="file-uploader"
                    action="http://localhost:3001/api/projects/upload"
                    :limit="1"
                    :on-preview="handlePreview"
                    :before-remove="beforeRemove"
                    :on-exceed="handleExceed"
                    :on-success="handleSuccess"
                    :file-list="finalFileList"
                  >
                    <el-button size="small" type="primary" v-if="isFinalReport && checkProjectOwner(postForm.id) && !isView">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip" v-if="isFinalReport && checkProjectOwner(postForm.id) && !isView">
                      .docs 文件小于500kb
                    </div>
                  </el-upload>
                </el-form-item>
              </el-row>
              <!-- <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  prop="projectFinalDate"
                  label-width="180px"
                  label="结项日期："
                >
                  <el-date-picker
                    v-model="postForm.projectFinalDate"
                    type="date"
                    placeholder="请选择结项日期"
                    :disabled="isMidReport || isFinalReport || isMidCheck || !checkPermission(['项目审批：结项'])"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  style="margin-bottom: 40px"
                  label-width="180px"
                  label="结项说明："
                >
                  <el-input
                    v-model="postForm.projectFinalDescription"
                    type="textarea"
                    class=""
                    :autosize="{ minRows: 4, maxRows: 8 }"
                    placeholder="请输入结项说明"
                    :disabled="isMidReport || isFinalReport || isMidCheck || !checkPermission(['项目审批：结项'])"
                  />
                </el-form-item>
              </el-row> -->
            </el-row>
          </el-collapse-item>
        </el-collapse>
        <div class="approve-container" v-if="this.isMidCheck || this.isFinalCheck">
        <div class="approve-approver-container">
           <div class="approve-type-title">{{ approveType }}:</div>
        </div>
        <div class="approve-divider"></div>
        <div class="approve-action-container">
            <el-row>
            <el-form-item
                  style="margin-bottom: 40px"
                  prop="researcherHonor"
                  label-width="180px"
                  label="操作："
                >
                <template>
            <el-radio
                v-model="approveStatus"
                label="通过"
             >通过</el-radio>
            <el-radio
                v-model="approveStatus"
                label="驳回"
            >驳回</el-radio>
        </template>
        </el-form-item>
        <el-form-item
                  style="margin-bottom: 40px"
                  label-width="180px"
                  label="意见："
                >
                  <el-input
                    v-model="approveComment"
                    type="textarea"
                    class=""
                    :autosize="{ minRows: 4, maxRows: 8 }"
                    placeholder="请输入审批意见"
                  />
                </el-form-item>
            </el-row>
            <el-row>
                <el-button
          v-loading="loading"
          style="margin-left: 180px; width: 100px"
          type="success"
          @click="approveForm"
        >
          确认
        </el-button>
        <el-button
          v-loading="loading"
          style="margin-left: 100px; width: 100px"
          type="success"
          @click="$router.push(`/project/approve/list`)"
        >
          返回
        </el-button>
            </el-row>
        </div>
      </div>
      </div>

      <el-button
        v-if="this.isMidReport || this.isFinalReport"
        v-loading="loading"
        style="margin-left: 230px; width: 100px"
        type="success"
        @click="submitForm"
      >
        保存
      </el-button>
    </el-form>
  </div>
</template>

<script>
import { fetchProjectById, updateProject, updateProjectApprove } from "@/api/project";
import { mapGetters } from "vuex";
import { checkProjectOwner } from '@/utils/permission';
import { generateNewDate } from '@/utils/date';

const defaultForm = {
  projectId: "", // 项目编号
  projectName: "", // 项目名称
  projectDeclareId: null,// 项目申报题目id
  projectDeclareName: "", // 项目申报题目
  projectGroupId: null, // 课题组id
  projectGroupName: "", // 课题组名称
  projectOwnerId: null, // 项目负责人ID
  projectOwnerEmployeeId: "", // 项目负责人编号
  projectOwnerName: "", // 项目负责人名字
  projectOwnerPhone: "", // 项目负责人电话
  projectOwnerEmail: "", // 项目负责人邮箱
  projectDepartment: "", // 项目所属部门
  projectSource: "",
  projectCategory: "",
  projectLevel: "",
  projectDirection: "",
  projectResearchDirection: "",
  projectStatus: "", // 项目状态
  projectDeclareDate: null,
  projectCreatedDate: null,
  projectStartDate: null,
  projectExpectedEndDate: null,
  projectEndDate: null,
  projectApprovedCost: null, // 项目已批准经费
  projectAppliedCost: null,
  projectAppliedCostUse: '', // 项目已使用经费
  projectAppliedCostUseItems: [], // 项目已使用经费
  projectAppliedCostItems: [],
  projectResultForm: "",
  projectStatisticalYear: null, // 项目统计年度
  projectAttachFileName: "", // 项目立项报告名字
  projectAttachFileUrl: "", // 项目立项报告地址
  projectChangeReport: "", // 项目变更证明材料
  projectChangeReportName: "", // 项目变更证明材料名称
  projectChangeDescription: "", // 项目变更说明
  projectEthicalApproverId1: null,
  projectEthicalApproverName1: "",
  projectEthicalApproverId2: null,
  projectEthicalApproverName2: "",
  projectCostApproverId: null,
  projectCostApproverName: "",
  projectPreApproverId: null,
  projectPreApproverName: "",
  projectEndApproverId: null,
  projectEndApproverName: "",
  projectApplicantId: null,
  projectApplicantName: "",
  projectInformationCheckStatus: "", // 项目信息审核状态
  projectInformationCheckHistory: null,
  projectMidReportName: "", // 项目中检文件名
  projectMidReport: "", // 项目中检报告
  projectMidDate: null, // 项目中检日期
  projectMidDescription: "", // 项目中检说明
  projectFinalReportName: "", // 项目结项文件名
  projectFinalReport: "", // 项目结项报告
  projectFinalDate: null, // 项目结项日期
  projectFinalDescription: "", // 项目结项说明
  projectMidApproverId: null, // 项目中检者ID
  projectMidApproverName: "", // 项目中检者名字
  projectFinalApproverId: null, // 项目结项者ID
  projectFinalApproverName: "", // 项目结项者名字
  projectCheckStatus: "提交项目中检报告", // 项目审批状态
  projectCheckHistory: null, // 项目审批履历
  projectChangeHistory: null,
  projectChangeStatus: null, // 项目变更状态
  projectEthicCheckCount: 0, // 伦理审批通过个数
  action: "",
  id: undefined,
};

export default {
  name: "ProjectCheckDetail",
  props: {
    isView: {
      type: Boolean,
      default: false,
    },
    isMidReport: {
      type: Boolean,
      default: false,
    },
    isFinalReport: {
      type: Boolean,
      default: false,
    },
    isMidCheck: {
      type: Boolean,
      default: false,
    },
    isFinalCheck: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      approveType: "", // 中检审批，结项审批
      approveStatus: "通过",
      approveComment: "",
      activeNames: ["1"],
      midFileList: [],
      finalFileList: [],
    };
  },
  computed: {
    ...mapGetters(["id", "name", "roles"]),
  },
  created() {
    const id = this.$route.params && this.$route.params.id;
    if (this.isMid) {
      this.approveType = "中检审批";
    } else if (this.isEnd) {
      this.approveType = "结项审批";
    }
    this.fetchData(id);
  },
  methods: {
    checkProjectOwner,
    handlePreview(file) {
      let a = document.createElement('a');
      let event = new MouseEvent('click');
      a.download = file.name;
      a.href = file.response? `http://localhost:3001/${file.response.srcurl}` : file.url;
      a.dispatchEvent(event);
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `文件数量限制为1, 您选择了 ${files.length} 个文件。`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`删除 ${file.name} ?`);
    },
    async handleSuccess(res, file) {
      if (res.status === "1") return this.$message.error(res.message);
      if (this.isMidReport) {
        this.postForm.projectMidReport = `http://localhost:3001/${res.srcurl}`;
        this.postForm.projectMidReportName = file.name;
      } else if (this.isFinalReport) {
        this.postForm.projectFinalReport = `http://localhost:3001/${res.srcurl}`;
        this.postForm.projectFinalReportName = file.name;
      }
    },
    addItem(val) {
      this.postForm.projectAppliedCostUseItems.push({
        index: val + 1,
        id: null,
        name: null,
        appropriation: null,
        startDate: null,
        endDate: null,
      });
    },
    computedMoney() {
      this.postForm.projectAppliedCostUse = this.postForm.projectAppliedCostUseItems.reduce(
          (acc, cur) => {
            return acc + Number(cur.appropriation);
          },
          0
      );
    },
    removeItem(itemIndex) {
      console.log(`remove${itemIndex}`)
      if (this.postForm.projectAppliedCostUseItems.length > 1) {
        this.postForm.projectAppliedCostUseItems.splice(itemIndex, 1);
      } else {
        this.postForm.projectAppliedCostUseItems = [{
          index: 0,
          id: null,
          name: null,
          appropriation: null,
          startDate: null,
          endDate: null,
        }];
      }
      this.caculateTotalCost();
    },
    caculateTotalCost() {
      let totalCost = 0;

      this.postForm.projectAppliedCostUseItems.forEach((item) => {
        totalCost += item.appropriation ? item.appropriation : 0;
      });
      this.postForm.projectAppliedCostUse = totalCost;
    },
    fetchData(id) {
      fetchProjectById(id)
        .then((res) => {
          this.postForm = res.data[0];
          this.postForm.projectAppliedCostItems =
              this.postForm.projectAppliedCostItems?.length > 0
                ? JSON.parse(this.postForm.projectAppliedCostItems)
                : [];
          this.postForm.projectAppliedCostUseItems =
              this.postForm.projectAppliedCostUseItems?.length > 0
                  ? JSON.parse(this.postForm.projectAppliedCostUseItems)
                  : [{
                    index: 0,
                    id: null,
                    name: null,
                    appropriation: null,
                    startDate: null,
                    endDate: null,
                  }];
          this.midFileList = this.postForm.projectMidReportName
            ? (this.midFileList = [
                {
                  name: this.postForm.projectMidReportName,
                  url: this.postForm.projectMidReport,
                },
              ])
            : [];
          this.finalFileList = this.postForm.projectFinalReportName
            ? (this.finalFileList = [
                {
                  name: this.postForm.projectFinalReportName,
                  url: this.postForm.projectFinalReport,
                },
              ])
            : [];
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submitForm() {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.isMidReport) {
            this.postForm.action = "midReport";
            this.postForm.projectCheckStatus = '项目中期报告审批中'
          } else if(this.isFinalReport) {
            this.postForm.action = "finalReport";
            this.postForm.projectCheckStatus = "项目结项报告审批中";
          }
          updateProject(this.postForm.id, this.postForm)
            .then((res) => {
              if (res.data) {
                if (this.isMidReport) {
                  this.$router.push("/project/mid/list");
                } else if(this.isFinalReport) {
                  this.$router.push("/project/final/list");
                }

                this.$message({
                  title: "成功",
                  message: "项目中检信息更新成功",
                  type: "success",
                  duration: 2000,
                });
              } else {
                this.$message({
                  message: "项目中检信息更新失败",
                  type: "error",
                });
              }
              this.loading = false;
            })
            .catch((err) => {
              this.loading = false;
            });
        } else {
          console.log("项目中检信息更新失败");
          return false;
        }
      });
    },
    approveForm() {
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true;

          if (this.isMidCheck) {
              // this.approveType = "中检审批";
              if (this.approveStatus === "通过") {
                this.postForm.projectCheckStatus = "提交项目结项报告";
              } else {
                this.postForm.projectCheckStatus = "项目中期报告审批驳回";
              }
              this.postForm.projectMidDate = generateNewDate();
              this.postForm.projectMidDescription = this.approveComment;
              this.postForm.projectMidApproverId = this.id;
              this.postForm.projectMidApproverName = this.name;
            } else if (this.isFinalCheck) {
              // this.approveType = "结项审批";
              if (this.approveStatus === "通过") {
                this.postForm.projectCheckStatus = "项目已结项";
                this.postForm.projectStatus = "项目已结项";
                this.postForm.projectEndDate = generateNewDate();
              } else {
                this.postForm.projectCheckStatus = "项目结项报告审批驳回";
              }
              this.postForm.projectFinalDate = generateNewDate();
              this.postForm.projectFinalDescription = this.approveComment;
              this.postForm.projectFinalApproverId = this.id;
              this.postForm.projectFinalApproverName = this.name;
            }
            updateProjectApprove(this.postForm.id,
              {projectForm: this.postForm, changeForm: null,
                isChange: false, isMemberChange: false}) // need to add
              .then((res) => {
                if (res.data) {
                  this.$router.push("/project/approve/list");
                  this.$message({
                    title: "成功",
                    message: "审批信息保成功",
                    type: "success",
                    duration: 2000,
                  });
                } else {
                  this.$message({
                    message: "审批信息保存失败",
                    type: "error",
                  });
                }
                this.loading = false;
              })
              .catch((err) => {
                this.loading = false;
              });
        } else {
          console.log("审批信息保存失败");
          return false;
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }
}

.identity-container {
  margin-top: 50px;
}

.approve-container {
    border: 1px solid #ebebeb;
    border-radius: 3px;

    .approve-approver-container {
      padding: 16px 0 16px 5px;
    }

    .approve-action-container {
        padding-bottom: 16px;;
      }

    .approve-divider {
      background-color: #fafafa;
      border-top: 1px solid #eaeefb;
      overflow: hidden;
      height: 0;
    }
  }
</style>
